<template>
    <div class="finance_box" ref="myElementRef">
      
      <div class="table_box">
        <vue-office-excel 
          :src="xlsxSrc" 
          style="height: 100vh;"
          @rendered="renderedHandler"
          @error="errorHandler"
        />
      </div>
      
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from "vue";
  import { ElMessage } from "element-plus";
  import VueOfficeExcel from '@vue-office/excel';
  import '@vue-office/excel/lib/index.css';
  import axios from 'axios';
  
  const xlsxSrc = ref('');
  const loading = ref(true);
  let blobUrl = null;
  
  // 通过代理获取文件，避免跨域问题
  onMounted(async () => {
    try {
      // 使用代理路径
      const proxyUrl = 'http://fhhxjimg.oss-cn-beijing.aliyuncs.com/test.xlsx';
      console.log('开始加载文件:', proxyUrl);
      
      const response = await axios.get(proxyUrl, {
        responseType: 'blob',
        timeout: 30000
      });
      
      console.log('文件加载成功，大小:', response.data.size);
      
      // 将 blob 转换为 URL
      blobUrl = URL.createObjectURL(response.data);
      xlsxSrc.value = blobUrl;
      loading.value = false;
    } catch (error) {
      console.error('加载文件失败:', error);
      loading.value = false;
      // 不设置 xlsxSrc，让组件显示错误状态
      ElMessage.error('文件加载失败，请检查网络连接或文件地址');
    }
  });
  
  // 组件卸载时清理 blob URL
  onUnmounted(() => {
    if (blobUrl) {
      URL.revokeObjectURL(blobUrl);
      blobUrl = null;
    }
  });
  
  const renderedHandler = () => {
    console.log('预览完成');
    loading.value = false;
  };
  
  const errorHandler = (e) => {
    console.log('预览失败', e);
    loading.value = false;
    ElMessage.error('文档预览失败');
  };
  </script>
  
  <style lang="less" scoped>
  .finance_box {
    flex: 1;
    overflow: auto;
    background-color: #fff;
    border-radius: 6px;
    padding: 10px;
    margin-right: 10px;
  }
  
  .btn_box {
    height: 40px;
    display: flex;
  }
  
  .table_box {
    width: 100%;
  }

  </style>
  